//
//  AppDelegate.m
//  LKIntelligentVideoProject
//
//  Created by she1323 on 2018/9/10.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "AppDelegate.h"
#import "LKSwitchRootVcTool.h"
#import "CYLaunchAnimateViewController.h"
#define BMKAppkey @"Xs8oK7p5KvjwoCLmU8d1GfwErmCiZ5Ru"

//#import <Mcu_sdk/MCUVmsNetSDK.h>
//#import <Mcu_sdk/VideoPlaySDK.h>
#import "LKPushSetModel.h"

// iOS10注册APNs所需头文件

//#define pushAppkey @"eda9a06ff04e87e13f24a30d"


#define pushAppkey @"037983d05090a9a32e5cb8a5"
//#define pushAppkey @"3c3c1fd37c2d622b673b52e1"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<BMKLocationAuthDelegate,JPUSHRegisterDelegate>

@property (nonatomic, strong) BMKMapManager *mapManager; //主引擎类

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
 //设置海康威视的rtsp流的播放SDK初始化
//    [[MCUVmsNetSDK shareInstance] configMspWithAddress:@"" port:@""];
//    //初始化SDK
//    VP_InitSDK();
//    //设置是否开启取流日志打印，默认不开启
//    VP_SetPrint(NO);
    
    
    NSLog(@"程序启动");
    //配置百度地图
    [self configBMKMap];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [LKSwitchRootVcTool switchRootController];
    [self.window makeKeyAndVisible];
    [self setNavgationBarStyle];
    
    
    
    // 注册APNS
    [self initAPNS];
    // 初始化push
    [self initPush:launchOptions];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"enablePush"] != nil) {
     
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"enablePush"] isEqual:@(YES)]) {

        }else{
            [[UIApplication sharedApplication] unregisterForRemoteNotifications];
        }
    }else{

    }
    // init launch view
    UIView *launchView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    launchView.backgroundColor = ColorRGB(163,171,166);
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"LOGOICON"];
    imageView.size = CGSizeMake(0.1, 0.1);
    imageView.center = CGPointMake(launchView.centerX, launchView.centerY - 70);
    [launchView addSubview:imageView];
    UILabel *controLabel = [[UILabel alloc] init];
//    controLabel.backgroundColor = [UIColor redColor];
    controLabel.center = CGPointMake(launchView.centerX - 60, launchView.centerY + 30);
    controLabel.size = CGSizeMake(120, 30);
//    controLabel.center = CGPointMake(launchView.centerX - 60, launchView.centerY + 100);
    controLabel.text = @"智享平台";
    controLabel.textColor = [UIColor whiteColor];
    controLabel.font = [UIFont systemFontOfSize:20];
    controLabel.textAlignment = NSTextAlignmentCenter;
    [launchView addSubview:controLabel];
    controLabel.transform = CGAffineTransformRotate(controLabel.transform, M_PI);
    [UIView animateWithDuration:1 animations:^{
        imageView.transform = CGAffineTransformMakeScale(1440, 1440);
        controLabel.transform = CGAffineTransformRotate(controLabel.transform, M_PI);
        launchView.backgroundColor = ColorRGB(52, 63, 56);
    }];
    // init CYLaunchAnimateViewController
    CYLaunchAnimateViewController *launchCtrl = [[CYLaunchAnimateViewController alloc]initWithContentView:launchView animateType:CYLaunchAnimateTypePointZoomOut2 showSkipButton:YES];
    [launchCtrl show];

    // Override point for customization after application launch.
    return YES;
}





/*极光推送的通知事件的初始化*/
/**
 设置推送事件
 */

// 接收到通知事件
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSLog(@"接受到的信息数据%@",userInfo);
    [LKPushSetModel setNewTagsWithInfo:userInfo];
}


- (void)initAPNS
{
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        if (@available(iOS 10.0, *)) {
            entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        } else {
            // Fallback on earlier versions
        }
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
}

- (void)initPush:(NSDictionary *)launchOptions
{
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:pushAppkey
                          channel:nil
                 apsForProduction:NO
            advertisingIdentifier:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}
// 当应用在前台运行中，收到远程通知时，会回调这个方法。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [JPUSHService handleRemoteNotification:userInfo];
}

#pragma mark - 通知相关
#pragma mark 在前台接受到通知会调用 / 当应用在后台状态时，点击push消息启动应用 (ios10在前台接收到不会调用)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 取得 APNs 标准信息内容
    
    //BOOL isActive;
    if (application.applicationState == UIApplicationStateActive) {
        //  isActive = YES;
    } else {
        //  isActive = NO;
        [self jumpToOther:userInfo];
    }
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)jumpToOther:(NSDictionary *)userInfo
{
    // 得到通知的内容
    [LKPushSetModel pushWithInfo:userInfo];
}

// 添加处理APNs通知回调方法
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
// iOS 10 在前台收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    } // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}


// iOS 10 Support
// App通知的点击事件
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self jumpToOther:userInfo];
    
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler();  // 系统要求执行这个方法
}


// 当客户端注册远程通知时，如果成功，则回调第一个，客户端把deviceToken取出来发给服务端，push消息的时候要用。
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [LKPushSetModel setUpMyPushInfo];
    [JPUSHService registerDeviceToken:deviceToken];
}




//横屏方法（无需调用）
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (self.fullScreen == YES) {
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}

/**
 设置导航栏的全局变量颜色
 */
-(void)setNavgationBarStyle{
    //设置导航条颜色 美团导航栏颜色
//    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:ColorRGB(45, 50, 72)];
    //设置导航条文字颜色 白色
//    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:COLOR_HEX(0x000000)}];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    //设置按钮文字颜色 白色
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    
    //设置导航栏按钮字体大小
    [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:18], NSFontAttributeName,nil] forState:UIControlStateNormal];
}
/**
 百度地图的配置
 */
-(void)configBMKMap{
    // 初始化定位SDK
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:@"Bp5Y094M92Mq5dq0YVwIXVy6i0XEBQY8" authDelegate:self];
    //要使用百度地图，请先启动BMKMapManager
    _mapManager = [[BMKMapManager alloc] init];
    
    /**
     百度地图SDK所有API均支持百度坐标（BD09）和国测局坐标（GCJ02），用此方法设置您使用的坐标类型.
     默认是BD09（BMK_COORDTYPE_BD09LL）坐标.
     如果需要使用GCJ02坐标，需要设置CoordinateType为：BMK_COORDTYPE_COMMON.
     */
    
    
    if ([BMKMapManager setCoordinateTypeUsedInBaiduMapSDK:BMK_COORDTYPE_BD09LL]) {
        NSLog(@"经纬度类型设置成功");
    } else {
        NSLog(@"经纬度类型设置失败");
    }
    
    //启动引擎并设置AK并设置delegate
    BOOL result = [_mapManager start:BMKAppkey generalDelegate:self];
    if (!result) {
        NSLog(@"启动引擎失败");
    }
}

/**
 联网结果回调
 
 @param iError 联网结果错误码信息，0代表联网成功
 */
- (void)onGetNetworkState:(int)iError {
    if (0 == iError) {
        NSLog(@"联网成功");
    } else {
        NSLog(@"联网失败：%d", iError);
    }
}

/**
 鉴权结果回调
 
 @param iError 鉴权结果错误码信息，0代表鉴权成功
 */
- (void)onGetPermissionState:(int)iError {
    if (0 == iError) {
        NSLog(@"授权成功");
    } else {
        NSLog(@"授权失败：%d", iError);
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
